<?php
class Post_model extends CI_Model{
	public function getPostsByViews(){
		$data = array();
		$this->db->select('p.*, u.user_name, c.category_name');
		$this->db->where('post_parent', 0);
		$this->db->order_by('post_view');
		$this->db->from('posts AS p');
		$this->db->join('users AS u','p.post_author = u.ID');
		$this->db->join('categories c','c.ID = p.post_category');
		$this->db->limit(5);
		$q = $this->db->get();
		
		if($q->num_rows()){
			$data = $q->result();
		}
		
		$q->free_result();
		return $data;
	}
	
	public function getPostById($id){
		
		$query =  $this->db->get_where('posts', array('id' => $id));
		$object = $query->result();
		$query->free_result();
		return $object[0];
	}
	
	public function getNewestPosts(){
		$data = array();
		$this->db->select('p.*, u.user_name, c.category_name');
		$this->db->where('post_parent', 0);
		$this->db->order_by('post_datetime','desc');
		$this->db->from('posts AS p');
		$this->db->join('users AS u','p.post_author = u.ID');
		$this->db->join('categories c','c.ID = p.post_category');
		$this->db->limit(10);
		$q = $this->db->get();
		
		if($q->num_rows()){
			$data = $q->result();
		}
		
		$q->free_result();
		return $data;
	}
	
	public function getPostByUser($userid){
		$this->db->select('p.*');
		$this->db->where(array(
					'post_author' => $userid,
					'post_status' => 1,
					'post_parent' => 0
		));
		$this->db->from('posts AS p');
		$this->db->order_by('post_datetime','desc');
		
		$query = $this->db->get();
		
		$data = NULL;
		$data = $query->result();
		$query->free_result();
		return $data;
		
	}
	
	public function getAnswersByPostId($id){
		$this->db->select('p.ID, u.user_name, p.post_datetime, p.post_content');
		$this->db->from('posts p');
		$this->db->where('p.post_parent',$id);
		$this->db->where('p.post_status','1');
		$this->db->join('users u','u.ID = p.post_author');
		$this->db->order_by('p.post_datetime','desc');
		$q = $this->db->get();
		
		$data = $q->result();
		$q->free_result();
		return $data;
	}
	
	public function getPostWithSameCategory($post_category){
		
		$this->db->select('p.*');
		$this->db->from('posts p');
		$this->db->where('p.post_category',$post_category);
		$this->db->where('p.post_status',1);
		$this->db->where('p.post_parent',0);
		$this->db->order_by('p.post_view','desc');
		$this->db->limit(5);
		$q = $this->db->get();
		
		$data = $q->result();
		
		$q->free_result();
		
		return $data;
		
						
	}
	
	public function insert($post_title,$post_content,$post_category,$post_parent = 0){
		
		$data = array(
			'post_author' => $this->session->userdata('user'),
			'post_content' => $post_content,
			'post_title' => $post_title,
			'post_status' => '1',
			'post_parent' => $post_parent,
			'post_type' => '1',
			'post_view'=> '0',
			'post_category' => $post_category			
		);
		try {
			$this->db->insert('posts', $data);	
		} catch (Exception $e) {
			return 0;
		}
		return 1;
		 
	}
}